package cre.sample.test.lock.reentrant;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 一种简单的自旋锁
 *
 * Created by CreGu on 2016/6/18.
 */
public class SpinLock {
    //    原子引用对象
    private AtomicReference<Thread> sign = new AtomicReference<Thread>();

    public void lock(){
        Thread currentThread=Thread.currentThread();
//        当前锁没有持有者时，才将当前线程设置为锁的持有者
        while (!sign.compareAndSet(null, currentThread)) {
            System.out.printf("锁已经被持有了，当前线程%s轮询（自旋）\n", currentThread);
        }
    }

    public void unlock(){
        Thread currentThread=Thread.currentThread();
//        CAS函数，当前线程为锁的持有者时，设置才会成功，这个是CAS操作保证的
        sign.compareAndSet(currentThread, null);
    }
}
